package com.gvsoft.conns;

import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgRouting
 * Author: zhaoqiubo
 * Date: 15/8/13
 * Time: 上午10:07
 * Desc: 连接管理工具类
 */
public class GVConnTools {

    private static Map<String, GVConnection> CONNECTION_BY_USERID = new ConcurrentHashMap<String, GVConnection>();
    private static Map<String, GVConnection> CONNECTION_BY_TOKEN = new ConcurrentHashMap<String, GVConnection>();

    private static Lock lock = new ReentrantLock();

    public static GVConnection getConnByToken(String token) {

        if (CONNECTION_BY_TOKEN.get(token) != null) {
            return CONNECTION_BY_TOKEN.get(token);
        } else {
            return null;
        }

    }

    public static GVConnection getConnByUserId(String userId) {

        return CONNECTION_BY_USERID.get(userId);

    }

    public static SocketChannel getChannelByUserId(String userId) {
        if (CONNECTION_BY_USERID.get(userId) != null) {
            return CONNECTION_BY_USERID.get(userId).getChannel();
        } else {
            return null;
        }

    }

    public static SocketChannel getChannelByToken(String token) {

        return CONNECTION_BY_TOKEN.get(token).getChannel();

    }

    public static synchronized void addConn2Cache(GVConnection conn) {

        CONNECTION_BY_TOKEN.put(conn.getToken(), conn);
        CONNECTION_BY_USERID.put(conn.getUserId(), conn);

    }

    public static void removeConnByUserId(String userId) {

        lock.lock();
        try {

            String token = CONNECTION_BY_USERID.get(userId).getToken();
            CONNECTION_BY_USERID.remove(userId);
            CONNECTION_BY_TOKEN.remove(token);

        } finally {
            lock.unlock();
        }
    }

    public static void removeConnByToken(String token) {

        lock.lock();
        try {

            String userId = CONNECTION_BY_TOKEN.get(token).getToken();
            CONNECTION_BY_TOKEN.remove(token);
            CONNECTION_BY_USERID.remove(userId);

        } finally {
            lock.unlock();
        }

    }

    public static String getUserIdByToken(String token) {

        return CONNECTION_BY_TOKEN.get(token).getUserId();

    }

    public static String getTokenByUserId(String userId) {

        return CONNECTION_BY_USERID.get(userId).getToken();

    }

    public static synchronized void updLastAccessTime(String token, int lastAccessTime) {

        String userId = CONNECTION_BY_TOKEN.get(token).getUserId();
        CONNECTION_BY_USERID.get(userId).setLastAccessTime(lastAccessTime);
        CONNECTION_BY_TOKEN.get(token).setLastAccessTime(lastAccessTime);

    }

    public static Map getConnCache() {
        return CONNECTION_BY_TOKEN;
    }

}
